﻿//==============================================================
//  Create by whl at 4/20/2014 12:08:50 PM.
//  Version 1.0
//  
//==============================================================


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cn.Finder.SDKFramework.Request;
using Cn.Finder.SDKFramework.Response;
using System.Threading;

namespace Cn.Finder.SDKFramework.Util
{

    

    /// <summary>
    /// 多线程发送请求 模板执行处理
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class RequestTemplateExecuter<T> where T : ApiResponse
    {

        #region 请求之前
        /// <summary>
        /// 调用请求之前 (一般显示进度 提示等)  主线程中执行
        /// </summary>
        /// <param name="response"></param>
        public delegate void PreRequestDelegate();
        public event PreRequestDelegate PreRequestEvent;

        #endregion


        #region 请求返回之后
        /// <summary>
        /// 请求返回之后调用  子线程中执行
        /// </summary>
        /// <param name="response"></param>
        public delegate void PostRequestDelegate();
        public event PostRequestDelegate PostRequestEvent;
        #endregion


        #region  调用成功处理

        /// <summary>
        /// 调用成功委托
        /// 
        /// if (this.InvokeRequired)
        ///   {
        ///      this.BeginInvoke(new RT.RequestSuccessDelegate(RequestSuccessDelegateFunc), new object[] { resp });
       ///  }
       ///   else
       ///    {
        ///          this.txtLog.Text = resp.Body;

         ///     }
        /// </summary>
        /// <param name="response"></param>
        public delegate void RequestSuccessDelegate(T response);
        /// <summary>
        /// 调用成功事件
        /// </summary>
        public event RequestSuccessDelegate RequestSuccessEvent;


        #endregion




        #region 调用失败处理
        /// <summary>
        /// 调用失败委托
        /// </summary>
        /// <param name="response"></param>
        public delegate void RequestFailureDelegate(T response);

        /// <summary>
        /// 调用失败事件
        /// </summary>
        public event RequestFailureDelegate RequestFailureEvent;

        #endregion






















        protected IClient client;
       

        public RequestTemplateExecuter(string url,string appKey,string appSecret):this(new DefaultClient(url,appKey,appSecret))
        {
            
        }


        public RequestTemplateExecuter(IClient client)
        {
            this.client = client;
        }

     


        public void Execute()
        {
            Execute("");
        }


        public void Execute(string sessionKey)
        {
            Execute(sessionKey, DateTime.Now);
        }


        public void Execute(string session, DateTime timestamp)
        {
            T response = null;
            try
            {
                if(PreRequestEvent!=null)
                    PreRequestEvent();

                IRequest<T> request = CreateRequest();

                ParameterizedThreadStart parameterizedThreadStart = new ParameterizedThreadStart(delegate
                {

                    response = client.Execute(request, session);

                    
                    if (PostRequestEvent!=null)
                    {
                        PostRequestEvent();
                    }

                    

                    if (response.Message.StatusCode == Cn.Finder.SDKFramework.Domain.Message.StatusCode_OK)
                    {
                       // Success(response);
                        if(RequestSuccessEvent!=null)
                            RequestSuccessEvent(response);
                    }
                    else
                    {
                        //Failure(response);
                        if(RequestFailureEvent!=null)
                            RequestFailureEvent(response);
                    }
                });

                Thread requestThread = new Thread(parameterizedThreadStart);

                requestThread.Start();
            }
            catch
            {
                //Failure(response);
                if (RequestFailureEvent != null)
                    RequestFailureEvent(response);
            }

        }


        /// <summary>
        /// 构建IRequest
        /// </summary>
        /// <returns></returns>
        protected abstract IRequest<T> CreateRequest();


        /// <summary>
        /// 请求成功 - 子线程方法  如 对UI 进行更新 请使用 BeginInvoke 或者Invoke
        /// </summary>
        /// <param name="response"></param>
        /// 
        [Obsolete]
        protected void Success(T response)
        {
        }


        /// <summary>
        /// 请求失败- 子线程方法  如 对UI 进行更新 请使用 BeginInvoke 或者Invoke
        /// </summary>
        /// <param name="response"></param>
         [Obsolete]
        protected void Failure(T response)
        {
        }


    }
}
